package com.vrv.netmgr.assets.chart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.UrlPrefix;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.netmgr.R;

/**
 * 本地注册情况统计
 * @author zxb
 *
 */
public class RegisterStatActivityDemo extends Activity {

	
	/** 为统计图开辟的区域 */
	private LinearLayout layout;	
	List<Long> list = new ArrayList<Long>();
	/**
	 * 等待对话框
	 */
	private ProgressDialog progressDialog;	
	/**
	 * 查询
	 */
	private static final int QUERY = 3;
	private static final int NET_ERR = 4;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.alarm_region_statistics_layout);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);

		initView();
		progressDialog = ProgressDialog.show(RegisterStatActivityDemo.this, "",
				"查询中...", true, true);
				
		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer();
				handler.sendEmptyMessage(QUERY);
			}
		}).start();
	}
	
	/**
	 * 处理器
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY:
				buildBarChartView();
				break;
			case NET_ERR:
				Toast.makeText(RegisterStatActivityDemo.this, "网络连接失败",
						Toast.LENGTH_LONG).show();
				break;
			}
		}
	};

	private void initView() {
		TextView titleView = (TextView) findViewById(R.id.title_text);
		titleView.setText("本地注册情况统计");

		// 返回按钮
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setVisibility(View.VISIBLE);
		backBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});

		// 初始化chart的渲染位置
		layout = (LinearLayout) findViewById(R.id.bar_chart);
	}
	
	public void buildBarChartView(){
		/** 统计图所需数据 */
		String[] labels = new String[] { "", "设备总数", "应注册", "已注册", "在线设备", "安装杀毒", "在线装杀毒 " };
		Object[] vals = list.toArray();//new long[] { 0L, 349L, 0L, 116L, 135L, 8L, 0L };
		/** 柱形图 */
		GraphicalView barChartView;
        // 设定Y轴的值显示
		XYSeries ySeries = new XYSeries("设备数量");
		for (int i = 0; i < vals.length; i++) {
			ySeries.add(i, (Long)vals[i]);
		}
        // 初始化Y轴的数据集
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		dataset.addSeries(ySeries);
        // 设置渲染器
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setXTitle("设备统计");
		renderer.setAxisTitleTextSize(18);
		renderer.setLegendTextSize(18);
		renderer.setBackgroundColor(Color.TRANSPARENT);

		renderer.setMargins(new int[] { 40, 20, 40, 25 });
		renderer.setGridColor(Color.DKGRAY);
		renderer.setLabelsTextSize(18);
		renderer.setLabelsColor(Color.BLUE);
        renderer.setXLabelsColor(Color.BLACK);
		renderer.setYLabelsColor(0, Color.BLACK);
		renderer.setShowGrid(false);
		renderer.setXLabelsAlign(Align.CENTER);
		renderer.setYLabelsAlign(Align.CENTER);
		renderer.setXLabelsPadding(30);

		renderer.setBarSpacing(1);
		renderer.setXLabelsAngle(-20);
        renderer.setAxesColor(Color.BLUE);
		renderer.setMarginsColor(getResources().getColor(R.color.gray1));
		renderer.setPanEnabled(Boolean.TRUE, Boolean.FALSE);
        renderer.setClickEnabled(true);// 是否可点击
		renderer.setSelectableBuffer(10);// 点击区域大小
		renderer.setXAxisMax(7);
		renderer.setYAxisMax(500);

		// 设置对应的X轴的label
		for (int i = 0; i < labels.length; i++) {
			renderer.addXTextLabel(i, labels[i]);
		}
        XYSeriesRenderer yRenderer = new XYSeriesRenderer();
		yRenderer.setColor(Color.BLUE);
		yRenderer.setChartValuesTextSize(18);
		yRenderer.setChartValuesTextAlign(Align.CENTER);
		yRenderer.setDisplayChartValues(true);
		renderer.addSeriesRenderer(yRenderer);

		barChartView = ChartFactory.getBarChartView(this, dataset, renderer,
				Type.DEFAULT);
		layout.addView(barChartView, new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		barChartView.setOnClickListener(new BarChartClickListener());
	}
	
	private class BarChartClickListener implements View.OnClickListener{
		@Override
		public void onClick(View v) {
			// 获取当前点击点
			SeriesSelection seriesSelection = ((GraphicalView) v)
					.getCurrentSeriesAndPoint();
            if (seriesSelection != null) {
            	int x = (int) seriesSelection.getXValue();
				Toast.makeText(RegisterStatActivityDemo.this, "第" + x + "个点",
						Toast.LENGTH_SHORT).show();
			}				
		}
	}
	
	// 查询所有数据
	public void getDataFromServer() {
		Map<String, String> map = new HashMap<String, String>();
		boolean retVal = qryRegisterStat(map);
		if (!retVal)
			handler.sendEmptyMessage(NET_ERR);
	}
	
	public boolean qryRegisterStat(Map<String, String> map) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext()).getUrlPrefix();
	    String urlAddr = urlPrefix + "/deviceInfo/getLocalDeviceRegisterInfo.do";
		String response = httpClientToServer.doPost(urlAddr, map);
		if (HttpClientToServer.DO_POST_ERR.equals(response)
				|| HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");
			if (!retVal) return retVal;
			int count = jsonObj.getInt("totalRecords");
			if (count < 1) return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				list.add(0L);
				list.add(jObj.getLong("totalCount"));
				list.add(jObj.getLong("shouldRegistedCount"));
				list.add(jObj.getLong("registedCount"));
				list.add(jObj.getLong("runCount"));
				list.add(jObj.getLong("kvsCount"));
				list.add(jObj.getLong("onlineInstallKvs"));

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
